package com.business_clean.ui.fragment.attendance;

import static com.business_clean.app.config.Constant.TYPE_INIT_DATA;
import static com.business_clean.app.config.Constant.TYPE_INIT_LOAD_MORE;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.config.Constant;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.CustomViewExtKt;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.CheckListDataUtil;
import com.business_clean.app.uitl.DividerItemDecoration;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.weight.dialog.CustomAttendancePartShadowPopup;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.app.weight.dialog.PagerDrawerPopup;
import com.business_clean.data.initconfig.BaseStringNumEntity;
import com.business_clean.data.mode.attendance.AttendanceEntity;
import com.business_clean.data.mode.attendance.FilterAttendanceData;
import com.business_clean.data.mode.project.ProjectMangerList;
import com.business_clean.databinding.FragmentDateAttendanceBinding;
import com.business_clean.databinding.HeaderDateAttendanceBinding;
import com.business_clean.ui.activity.attendance.MyAttendanceActivity;
import com.business_clean.ui.activity.attendance.ProjectAttendanceActivity;
import com.business_clean.ui.adapter.BaseStringAdapter;
import com.business_clean.ui.adapter.BaseStringNumAdapter;
import com.business_clean.ui.adapter.attendance.DateAttendanceAdapter;
import com.business_clean.ui.adapter.attendance.DateAttendanceMonthAdapter;
import com.business_clean.viewmodel.request.AttendanceViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateAttendanceMonthFragment extends BaseFragment<AttendanceViewModel, FragmentDateAttendanceBinding> {


    private DateAttendanceMonthAdapter mAdapter;

    private int page = 1;
    private int requestType;
    private int types = 2;

    private String project_uuid = "";
    private String group_uuid = "";
    private String search_date = "";
    private String is_list = "1";

    private String status = "";


    private BaseStringNumAdapter stringAdapter = new BaseStringNumAdapter(1);

    private FilterAttendanceData filterAttendanceData = new FilterAttendanceData();

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        mAdapter = new DateAttendanceMonthAdapter();
        getMDatabind().list.recyclerView.addItemDecoration(new DividerItemDecoration(getMActivity()));
        CustomViewExtKt.initRecyclerViewVertical(getMDatabind().list.recyclerView, mAdapter);

        getMDatabind().header.tvProject.setText(App.appViewModelInstance.getProjectInfo().getValue().getProject_short_name());
        project_uuid = App.appViewModelInstance.getProjectInfo().getValue().getUuid();

        filterAttendanceData.setProject_uuid(project_uuid);


        if (getArguments() != null) {
            search_date = getArguments().getString("date_month");
            LogUtils.e("search_date days ->" + search_date);
            getMDatabind().header.tvDate.setText(search_date);
        } else {
            getMDatabind().header.tvDate.setText(TimeUtils.millis2String(TimeUtils.getNowMills(), "yyyy-MM"));
            search_date = getMDatabind().header.tvDate.getText().toString();
        }

        if (filterAttendanceData != null) {
            filterAttendanceData.setSearch_month(getMDatabind().header.tvDate.getText().toString());
        }

        getMDatabind().header.recyclerTag.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        getMDatabind().header.recyclerTag.setAdapter(stringAdapter);
        getMDatabind().header.recyclerTag.addItemDecoration(new MyGridSpacingItemDecoration(5, SizeUtils.dp2px(10), false));

        getTagList(null);

        stringAdapter.updateItem(0);

        if (!ProjectAttendanceActivity.isToday && 2 == types) {//说明是月考勤
            stringAdapter.updateItem(ProjectAttendanceActivity.position);
            changeStatus(ProjectAttendanceActivity.position);
        }

        getMDatabind().list.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                requestMore();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                requestOne();
            }
        });

    }


    @Override
    public void onRequestSuccess() {
        mViewModel.getAttendanceEntity().observe(this, new Observer<AttendanceEntity>() {
            @Override
            public void onChanged(AttendanceEntity data) {
                getTagList(data);
                switch (requestType) {
                    case TYPE_INIT_DATA:
                        // 根据数据来决定要显示哪一个状态的View
                        if (CheckListDataUtil.checkInitData(data.getList(), mAdapter, getMDatabind().list.refreshLayout)) {
                            mAdapter.setList(data.getList());
                        }
                        break;
                    case TYPE_INIT_LOAD_MORE:
                        // 根据数据来决定要显示哪一个状态的View
                        if (CheckListDataUtil.checkLoadMoreData(data.getList(), mAdapter, getMDatabind().list.refreshLayout)) {
                            mAdapter.addData(data.getList());
                        }
                        break;
                }
            }
        });
    }

    private void getTagList(AttendanceEntity data) {
        List<BaseStringNumEntity> strings = new ArrayList<>();
        if (data != null) {
            strings.add(new BaseStringNumEntity("在岗", "" + data.getAll_total(), "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("入职", "" + data.getEntry_total(), "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("离职", "" + data.getLeft_total(), "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("休息", "" + data.getRest_total(), "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("应出勤", "" + data.getShould_attendance_total(), "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("实出勤", "" + data.getActual_attendance_total(), "#E4F9F2", "#09BE89"));
            strings.add(new BaseStringNumEntity("休假", "" + data.getHoliday_total(), "#F5F2F9", "#A671CF"));
            strings.add(new BaseStringNumEntity("加班", "" + data.getOvertime_total(), "#EFF8FF", "#1890FF"));
            strings.add(new BaseStringNumEntity("旷工", "" + data.getAbsenteeism_total(), "#FFEFF2", "#FF4040"));
            strings.add(new BaseStringNumEntity("缺卡", "" + data.getQk_total(), "#FEF6F3", "#FE6B03"));
        } else {
            strings.add(new BaseStringNumEntity("在岗", "0", "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("入职", "0", "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("离职", "0", "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("休息", "0", "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("应出勤", "0", "#F8F7FC", "#8D8E99"));
            strings.add(new BaseStringNumEntity("实出勤", "0", "#E4F9F2", "#09BE89"));
            strings.add(new BaseStringNumEntity("休假", "0", "#F5F2F9", "#A671CF"));
            strings.add(new BaseStringNumEntity("加班", "0", "#EFF8FF", "#1890FF"));
            strings.add(new BaseStringNumEntity("旷工", "0", "#FFEFF2", "#FF4040"));
            strings.add(new BaseStringNumEntity("缺卡", "0", "#FEF6F3", "#FE6B03"));
        }
        stringAdapter.setList(strings);
    }

    @Override
    public void initObserver() {
        App.appViewModelInstance.getProjectInfo().observe(this, new Observer<ProjectMangerList>() {
            @Override
            public void onChanged(ProjectMangerList projectMangerList) {
                project_uuid = projectMangerList.getUuid();
                getMDatabind().header.tvProject.setText(projectMangerList.getProject_short_name());
                if (filterAttendanceData != null) {
                    filterAttendanceData.setProject_uuid(project_uuid);
                }
                getMDatabind().header.tvGroup.setText("全部小组");
                group_uuid = "";
                changeFilterData();
                requestOne();
                mViewModel.getGroupAll(project_uuid);
            }
        });
    }

    @Override
    public void lazyLoadData() {
        mViewModel.getGroupAll(null);
//        requestOne();
    }

    @Override
    public void onResume() {
        super.onResume();
        requestOne();
    }

    @Override
    public void onBindViewClick() {
        //要区分日  月
        getMDatabind().header.llDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar defInstance = Calendar.getInstance();
                if (!TextUtils.isEmpty(getMDatabind().header.tvDate.getText())) {
                    defInstance.setTime(TimeUtils.string2Date(getMDatabind().header.tvDate.getText().toString(), "yyyy-MM"));
                }

                CommonUtils.showDialogTimePickerView(getMActivity(), "", defInstance, Calendar.getInstance().get(Calendar.YEAR) - 1, Calendar.getInstance().get(Calendar.YEAR) + 1, null, null, CustomTimePickerPopup.Mode.YM, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        //要区分日  月 显示
                        getMDatabind().header.tvDate.setText(TimeUtils.date2String(date, "yyyy-MM"));
                        search_date = getMDatabind().header.tvDate.getText().toString();
                        if (filterAttendanceData != null) {
                            filterAttendanceData.setSearch_month(search_date);
                        }
                        changeFilterData();
                        requestOne();
                    }
                });
            }
        });

        //筛选
        stringAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                stringAdapter.updateItem(position);
                changeStatus(position);
                requestOne();
            }
        });

        //切换项目
        getMDatabind().header.llProject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
                    new XPopup.Builder(getContext())
                            .asCustom(new PagerDrawerPopup(getMActivity())).show();
                }
            }
        });

        //早班组
        getMDatabind().header.llGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPartShadow(v);
            }
        });
        //考勤
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("uuid", mAdapter.getData().get(position).getUser_uuid());
                ActivityForwardUtil.startActivity(MyAttendanceActivity.class, bundle);
            }
        });

    }

    private void showPartShadow(final View v) {
        if (mViewModel.getGroupMangerEntity().getValue() != null) {
            new XPopup.Builder(getActivity())
                    .atView(v)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow(BasePopupView popupView) {
                        }

                        @Override
                        public void onDismiss(BasePopupView popupView) {
                        }
                    })
                    .asCustom(new CustomAttendancePartShadowPopup(getActivity(), mViewModel.getGroupMangerEntity().getValue().getList(), new OnDialogSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            if (position == -1) {
                                group_uuid = "";
                                getMDatabind().header.tvGroup.setText("全部小组");
                            } else {
                                group_uuid = mViewModel.getGroupMangerEntity().getValue().getList().get(position).getUuid();
                                getMDatabind().header.tvGroup.setText(mViewModel.getGroupMangerEntity().getValue().getList().get(position).getGroup_name());
                            }
                            if (filterAttendanceData != null) {
                                filterAttendanceData.setGroup_uuid(group_uuid);
                            }
                            changeFilterData();
                            requestOne();
                        }
                    })).show();
        }
    }

    private void changeStatus(int position) {
        switch (position) {//状态 1休假 2实出勤 3缺卡 4旷工 5休息 6加班 10应出勤 11入职 12离职
            case 0:
                status = String.valueOf(position);
                break;
            case 1:
                status = "11";
                break;
            case 2:
                status = "12";
                break;
            case 3:
                status = "5";
                break;
            case 4:
                status = "10";
                break;
            case 5:
                status = "2";
                break;
            case 6:
                status = "1";
                break;
            case 7:
                status = "6";
                break;
            case 8:
                status = "4";
                break;
            case 9:
                status = "3";
                break;
        }
        if (filterAttendanceData != null) {
            filterAttendanceData.setStat_status(status);
        }
        changeFilterData();
    }


    private void changeFilterData() {
        App.appViewModelInstance.getFilterAttendanceData().setValue(filterAttendanceData);
    }

    private void requestOne() {
        requestType = TYPE_INIT_DATA;
        page = 1;
        mViewModel.getAttendanceStat(types, project_uuid, group_uuid, search_date, is_list, status);
    }

    private void requestMore() {
        requestType = TYPE_INIT_LOAD_MORE;
        page++;
        mViewModel.getAttendanceStat(types, project_uuid, group_uuid, search_date, is_list, status);
    }
}
